package com.bill.common.system.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.bill.common.system.dao.IBuyCreditsDAO;
import com.bill.common.system.dto.BuyCreditsDTO;
import com.bill.common.system.dto.BuyCreditsQueryDTO;
import com.bill.common.system.entity.BuyCredits;
import com.bill.common.system.entity.TransactionRecord;
import com.bill.common.user.dao.IRegisterUserDAO;
import com.bill.common.user.dto.RegisterUserDTO;
import com.bill.common.user.entity.RegisterUser;
import com.bill.common.user.service.IRegisterUserService;
import com.bill.common.utils.TranType;
import com.sinba.common.dto.PageDTO;

public class BuyCreditsService implements IBuyCreditsService {

	@Autowired
	private IBuyCreditsDAO buyCreditsDAO;
	@Autowired
	private IRegisterUserDAO registerUserDAO;
	@Autowired
	private IRegisterUserService registerUserService;
	@Autowired
	private ITransactionRecordService transactionRecordService;
	
	@Transactional
	public PageDTO findBuyCreditsPager(BuyCreditsQueryDTO qdto, String sord,
			String sidx) {
		// TODO Auto-generated method stub
		PageDTO pageDto = buyCreditsDAO.findBuyCreditsPager(qdto, sord, sidx);
		List<BuyCredits> list = pageDto.getData();
		List<BuyCreditsDTO> dtos = new ArrayList<BuyCreditsDTO>();
		for(BuyCredits entity : list ){
			BuyCreditsDTO dto = new BuyCreditsDTO();
			BuyCreditsDTO.entity2dto(entity, dto);
			dtos.add(dto);
		}
		pageDto.setData(dtos);
		return pageDto;
	}

	@Transactional
	public synchronized String creditsOpt(BuyCreditsDTO dto){
		//卖出
		if("sellCredits".equals(dto.getOptType())){
			return sellCredits(dto);
		}
		
		if("cleanSellCredits".equals(dto.getOptType())){
			return cleanSellCredits(dto);
		}
		
		if("buyCredits".equals(dto.getOptType())){
			return buyCredits(dto);
		}
		
		if("cleanBuyCredits".equals(dto.getOptType())){
			return cleanBuyCredits(dto);
		}
		
		if("confirm".equals(dto.getOptType())){
			return confirm(dto);
		}
		
		if("confirmBackHesk".equals(dto.getOptType())){
			return confirm(dto);
		}
		
		return "Operation failed, please try again(操作失败，请重试)!";
	}
	
	
	@Transactional
	public String sellCredits(BuyCreditsDTO dto) {
		// TODO Auto-generated method stub
		String loginName = dto.getLoginName();
		RegisterUser registerUser = registerUserDAO.findUniqueBy("loginName", loginName);
		if(registerUser!=null){
			//验证密保
			RegisterUserDTO registerUserDTO = new RegisterUserDTO(loginName,
					dto.getPasswordProblem(), dto.getPasswordAnswer());
			if (!registerUserService.checkPwdProblem(registerUserDTO)) {//验证密保是否正确
				return "Secret answer is not correct(密保答案不正确)!";
			}
			
			//一天只允许卖出一次
			if(buyCreditsDAO.todayIsBuy( loginName )){
				return "Failure to sell, sell only allowed once every day, thank you!(卖出失败，每天只允许卖出一次，谢谢!)";
			}
			Double balance = transactionRecordService.findUserBalance(dto.getLoginName(), "Dynamic");
			
			if(balance<dto.getBuyMoney()){
				return "Selling amount greater than the amount sold(卖出金额大于可卖出金额)!";
			}else{
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(loginName);
				tr.setTransactionObject("system");
				tr.setTransactionType(TranType.MaiChu);
				tr.setRemark("");
				transactionRecordService.updateTran(tr, "Dynamic", (dto.getBuyMoney()*0.95), "CUT");
				
				
				TransactionRecord tr1 = new TransactionRecord();
				tr1.setLoginName(loginName);
				tr1.setTransactionObject("system");
				tr1.setTransactionType(TranType.MaiChuShouXuFei);
				tr1.setRemark("");
				transactionRecordService.updateTran(tr1, "Dynamic", (dto.getBuyMoney()*0.05), "CUT");
				
				BuyCredits entity = new BuyCredits();
				BuyCreditsDTO.dto2entity(dto, entity);
				entity.setBuyTime(new Date());
				entity.setStatus(0);
				entity.setLinkCode(registerUser.getLinkcode());
				entity.setAccountType(registerUser.getAccountType());
				entity.setBankAccount(registerUser.getBankAccount());
				entity.setLoginUserName(registerUser.getUserName());
				buyCreditsDAO.save(entity);
			}
			
			
		}else{
			return "Sell member does not exist, please check!(卖出会员不存在，请检查!)";//申请的会员不存在!
		}	
		
		return "Sell successfully, the operations center will be buying, please be patient(卖出成功，运营中心将会进行买入，请耐心等待)!";
	}
	
	@Transactional
	public String cleanSellCredits(BuyCreditsDTO dto) {
		// TODO Auto-generated method stub
		BuyCredits entity = buyCreditsDAO.findById(dto.getId());
		if(entity!=null){
			if(entity.getStatus()==0){
				entity.setOperationsCenter(null);
				entity.setOperationsCenterUserName(null);
				entity.setConfirmTime(null);
				entity.setStatus(4);
				buyCreditsDAO.merge(entity);
				
				TransactionRecord tr = new TransactionRecord();
				tr.setLoginName(entity.getLoginName());
				tr.setTransactionObject("System");
				tr.setTransactionType(TranType.MaiChuClean);
				tr.setRemark("");
				transactionRecordService.updateTran(tr, "Dynamic", entity.getBuyMoney(), "ADD");
				
			}else{
				return "Has begun trading is not permitted to sell Cancel(已开始交易，不允许卖出取消)！";
			}
		}else{
			return "Operation failed, please try again(操作失败，请重试)!";
		}
		return "Sell canceled successfully(卖出取消成功)!";
	}
	
	

	@Transactional
	public String buyCredits(BuyCreditsDTO dto) {
		// TODO Auto-generated method stub
		RegisterUser user1 = registerUserDAO.findUniqueBy("loginName", dto.getOperationsCenter());
		if(user1!=null && user1.isDeclarationCenter()){
			BuyCredits entity = buyCreditsDAO.findById(dto.getId());
			if(entity!=null){
				if(entity.getStatus()==0){
					entity.setOperationsCenter(dto.getOperationsCenter());
					entity.setOperationsCenterUserName(user1.getUserName());
					entity.setConfirmTime(new Date());
					entity.setStatus(1);
					buyCreditsDAO.merge(entity);
				}else{
					return "This operations center has been sold to buy, please refresh the page to check, thank you(此卖出已有运营中心买入，请刷新页面检查，谢谢)！";
				}
			}else{
				return "Operation failed, please try again(操作失败，请重试)!";
			}
		}else{
			return "BUY failed operations center does not exist, please check(买入失败，运营中心不存在，请检查)!";
		}
		
		
		return "BUY successful operation, please contact play money and sell side to confirm, thank you(买入操作成功，请及时打款并联系卖出方确认，谢谢)！";
		
	}
	
	
	@Transactional
	public String cleanBuyCredits(BuyCreditsDTO dto) {
		// TODO Auto-generated method stub
		BuyCredits entity = buyCreditsDAO.findById(dto.getId());
		if(entity!=null){
			if(entity.getStatus()==1){
				entity.setOperationsCenter(null);
				entity.setOperationsCenterUserName(null);
				entity.setConfirmTime(null);
				entity.setStatus(0);
				buyCreditsDAO.merge(entity);
			}else{
				return "It has been successful transaction, no longer allowed to cancel(已交易成功，不允许再取消)！";
			}
		}else{
			return "Operation failed, please try again(操作失败，请重试)!";
		}
		return "Buy Cancel success(买入取消成功)!";
	}
	

	@Transactional
	public String confirm(BuyCreditsDTO dto) {
		// TODO Auto-generated method stub
		
		BuyCredits entity = buyCreditsDAO.findById(dto.getId());
		if(entity.getStatus()==1){
			entity.setCompleteTime(new Date());
			entity.setStatus(2);
			buyCreditsDAO.merge(entity);
			
			TransactionRecord tr = new TransactionRecord();
			tr.setLoginName(entity.getOperationsCenter());
			tr.setTransactionObject(entity.getLoginName());
			tr.setTransactionType(TranType.MaiRu);
			tr.setRemark("");
			transactionRecordService.updateTran(tr, "Dynamic", entity.getBuyMoney(), "ADD");
		}else{
			return "It has been confirmed and check retry(操作失败,请检查重试)!";
			
		}
		return "Confirm successful completion of the transaction(确认成功，交易完成)!";
	}
	
	
	

	
	
}
